<template>
  <div class="profile">
    <div class="avatar-section">
      <div class="avatar-container" @mouseover="isHovering = true" @mouseleave="isHovering = false">
        <img :src="userStore.getUserInfo().avatar?userStore.getUserInfo().avatar:avatarUrl" alt="用户头像" class="avatar" />
        <el-button v-show="isHovering" class="change-avatar-btn" @click="changeAvatar">更换头像</el-button>
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          accept="image/*"
          @change="handleFileChange"
        />
      </div>
      <div class="user-info">
        <p>账号: {{ user.account }}</p>
        
        <!-- 非编辑状态 -->
        <div v-if="!isEditing">
          <p>昵称: {{ user.nickname }}</p>
          <p>电话: {{ user.phone || '未设置' }}</p>
          <p>地址: {{ user.address || '未设置' }}</p>
          <el-button type="primary" @click="startEdit">修改</el-button>
        </div>

        <!-- 编辑状态 -->
        <div v-else>
          <div class="edit-item">
            <span>昵称:</span>
            <el-input v-model="user.nickname" placeholder="请输入昵称"></el-input>
          </div>
          <div class="edit-item">
            <span>电话:</span>
            <el-input v-model="user.phone" placeholder="请输入电话号码"></el-input>
          </div>
          <div class="edit-item">
            <span>地址:</span>
            <el-input v-model="user.address" placeholder="请输入地址"></el-input>
          </div>
          <div class="button-group">
            <el-button type="primary" @click="saveEdit">保存</el-button>
            <el-button @click="cancelEdit">取消</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="username-section">
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import {useUserStore} from "@/stores/user";
import {updateAvatarAPI, updateUserInfoAPI} from "@/apis/user";

const avatarUrl = ref('https://tse2-mm.cn.bing.net/th/id/OIP-C.v3ywLkq_yuiisLQpDZ9wagHaGk?w=245&h=217&c=7&r=0&o=5&dpr=1.3&pid=1.7'); // 默认头像
const userStore=useUserStore()
const user = ref({
  account: userStore.getUserInfo().username,
  username: '默认用户名',
  nickname: userStore.getUserInfo().name,
  phone: userStore.getUserInfo().phone || '',
  address: userStore.getUserInfo().address || ''
});

// 修改为单个编辑状态
const isEditing = ref(false);

// 临时存储编辑前的所有值
const tempValues = ref({});

const isHovering = ref(false);

// 添加文件输入框引用
const fileInput = ref(null);

function startEdit() {
  tempValues.value = { ...user.value };
  isEditing.value = true;
}

async function saveEdit() {
  // 验证
  if (user.value.nickname === '') {
    ElMessage.error('昵称不能为空！');
    return;
  }

  if (user.value.nickname.length > 15) {
    ElMessage.error('昵称长度不能超过15位！');
    return;
  }

  if (user.value.phone && !/^1[3-9]\d{9}$/.test(user.value.phone)) {
    ElMessage.error('请输入有效的手机号码！');
    return;
  }

  try {
    const newUserInfo = userStore.getUserInfo();
    newUserInfo.name = user.value.nickname;
    newUserInfo.phone = user.value.phone;
    newUserInfo.address = user.value.address;
    
    await updateUserInfoAPI(JSON.stringify(newUserInfo)).then(res => {
      ElMessage({
        type: res.code === '200' ? 'success' : 'error',
        message: res.code === '200' ? '保存成功' : res.msg
      });
      if (res.code === '200') {
        isEditing.value = false;
      } else {
        Object.assign(user.value, tempValues.value);
      }
    });
  } catch (error) {
    Object.assign(user.value, tempValues.value);
    ElMessage.error(`保存失败: ${error.message}`);
  }
}

function cancelEdit() {
  Object.assign(user.value, tempValues.value);
  isEditing.value = false;
}

function changeAvatar() {
  // 触发文件选择
  fileInput.value.click();
}

async function handleFileChange(event) {
  const file = event.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件！');
    return;
  }

  // 验证文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB！');
    return;
  }

  try {
    // 创建 FormData 对象
    const formData = new FormData()
    formData.append('uid',userStore.getUserInfo().uid)
    formData.append('file', file)
    // 调用后端头像上传
    const response = await updateAvatarAPI(formData);
    if (response.code === '200') {

      ElMessage.success('头像更新成功');
      userStore.getUserInfo().avatar=response.data
    }
  } catch (error) {
    ElMessage.error(`上传失败: ${error.message}`);
  } finally {
    // 清除文件输入框的值，允许重复选择同一文件
    event.target.value = '';
  }
}

function submitForm() {
  // 提交表单逻辑
  ElMessage.success('用户名已保存');
}
</script>

<style scoped>
.profile {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 20px;
  margin: 0 auto;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 20px;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

.avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  margin-bottom: 10px;
  border: 2px solid rgba(216, 218, 219, 0.35);
  transition: transform 0.3s;
}

.avatar-container:hover .avatar {
  transform: scale(1.05);
}

.change-avatar-btn {
  position: absolute;
  top: 90%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
}

.avatar-container:hover .change-avatar-btn {
  display: block;
}

.user-info {
  margin-top: 10px;
}

.username-section {
  width: 100%;
}

.el-button {
  margin-top: 10px;
}

.el-form-item {
  margin-bottom: 20px;
}

.edit-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.edit-item span {
  width: 60px;
  margin-right: 10px;
}

.edit-item .el-input {
  width: 300px;
}

.button-group {
  margin-top: 20px;
}

.button-group .el-button {
  margin-right: 10px;
}
</style> 